﻿using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using ThresholdAssistant.Autofac;
using ThresholdAssistant.DataContract.Result;
using ThresholdAssistant.NLogSdk;
using ThresholdAssistant.WebAPI.Models;
using ThresholdAssistant.WebAPI.Models.Constants;

namespace ThresholdAssistant.WebAPI.Service
{
    /// <summary>
    /// 
    /// </summary>
    public class WeChatService : BaseService, IBaseAutofac
    {
        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        public async Task<ContractResult<string>> GetAccessTokenAsync()
        {
            var result = new ContractResult<string>();
            var token = await GetAccessToken();
            return result.SetSuceccful(token);
        }

        /// <summary>
        /// 发送模版消息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ContractResult> SendTemplateMessageAsync(SendTemplateMessageParam param)
        {
            //todo 发送模版消息要验证小程序参数设置用户是否接收
            var result = new ContractResult();
            if (string.IsNullOrWhiteSpace(param.OpenId))
            {
                param.OpenId = "o3G8K7obshquQM_RaA58RE32okY4";
            }
            //if (string.IsNullOrWhiteSpace(param.TemplateId))
            //{
            //    param.TemplateId = "VFYf-gjzcRejNvbrUljXc0eS_PJbLBgW_S2m20Ngddk";//目前只针对这种模版
            //}
            var token = await GetAccessToken();
            var url = $"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={token}";
            var json = new TemplateMessage
            {
                ToUser = param.OpenId,
                TemplateId = "VFYf-gjzcRejNvbrUljXc0eS_PJbLBgW_S2m20Ngddk",//目前只针对这种模版
                Data = new TemplateMessageData
                {
                    Thing1 = new TemplateMessageDataValue { Value = "阈值预警提醒" },
                    Time2 = new TemplateMessageDataValue { Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
                    Thing4 = new TemplateMessageDataValue { Value = "这是一条测试模板消息" }
                }
            };
            var rsp = await HttpClientHelp.PostAsync<TemplateMessage, WechatTemplateMessageResponse>(url, json);
            if (rsp.ErrCode == 0)
            {
                return result.SetSuceccful();
            }
            else
            {
                return result.SetError(ErrorResultEnum.RequestApiFail);
            }
        }

        /// <summary>
        /// 获取微信AccessToken
        /// </summary>
        /// <returns></returns>
        private async Task<string> GetAccessToken()
        {
            var token = await _cache.GetAsync<string>(RedisConstant.AccessTokenKey);
            if (!string.IsNullOrWhiteSpace(token))
            {
                return token;
            }
            string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={AppSettingConstant.WechatAuthLoginGonfig.AppId}&secret={AppSettingConstant.WechatAuthLoginGonfig.Secret}";
            var rlt = await HttpClient.GetAsync(url);
            var message = await rlt.Content.ReadAsStringAsync();
            if (string.IsNullOrWhiteSpace(message))
            {
                NLogUtil.Error($"获取微信AccessToken失败，返回结果：{message}");
                return "";
            }
            var rsp = JsonConvert.DeserializeObject<WechatAccessTokenResponse>(message);
            token = rsp.AccessToken;
            await _cache.SetNxAsync(RedisConstant.AccessTokenKey, token, rsp.ExpiresIn - 10);
            return token;
        }
    }
}
